import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:feature_projects/feature_config.dart';
import 'package:feature_projects/projects/view/project_item_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it/get_it.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'effect.dart';
import 'event.dart';
import 'state.dart';
import 'view_model.dart';

class ProjectsPage extends StatefulWidget {
  final ProjectsFeatureConfig config;

  const ProjectsPage({super.key, required this.config});

  @override
  State<ProjectsPage> createState() => _ProjectsPageState();
}

class _ProjectsPageState extends State<ProjectsPage>
    with AutomaticKeepAliveClientMixin {
  final _refreshController = RefreshController();

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BlocProvider(
      create: (BuildContext context) =>
          ProjectsViewModel(useCase: GetIt.I.get())..add(InitEvent()),
      child: SafeArea(
        child: Builder(builder: (context) => _buildPage(context)),
      ),
    );
  }

  Widget _buildPage(BuildContext context) {
    return BlocBuilder<ProjectsViewModel, ProjectsState>(
      builder: (context, state) {
        final viewModel = context.read<ProjectsViewModel>();
        final state = viewModel.state;

        // 在 BlocBuilder 中监听 sideEffects
        viewModel.sideEffects.listen((effect) {
          switch (effect) {
            case RefreshingFinished():
              debugPrint('RefreshingFinished');
              _refreshController.refreshCompleted();
              break;
            case LoadingMoreFinished():
              debugPrint('LoadingMoreFinished');
              _refreshController.loadComplete();
              break;
          }
        });
        return Stack(
          children: [
            SmartRefresher(
              controller: _refreshController,
              enablePullUp: true,
              enablePullDown: true,
              onRefresh: () {
                viewModel.sendEvent(RefreshEvent());
              },
              onLoading: () {
                viewModel.sendEvent(LoadMoreEvent());
              },
              child: ListView.separated(
                itemBuilder: (context, index) {
                  final model = state.list[index];
                  return ProjectItemView(
                    project: model,
                    onTapItem: () {
                      widget.config.navigateToWebview(model.title, model.link);
                    },
                    onTapSameChapter: () {},
                  );
                },
                separatorBuilder: (context, index) {
                  return SizedBox(height: 12.h);
                },
                itemCount: state.list.length,
              ),
            ),
            if (state.isLoading) ...{
              const CircularProgressIndicator().center(),
            },
          ],
        );
      },
    );
  }
}
